# -*- encoding=utf8 -*-

__author__ = "code哥"
import os
from sanic.blueprints import Blueprint
from sanic.views import HTTPMethodView
from sanic import response
from sanic_openapi import doc

blueprint = Blueprint(__name__, '/api')


class APPDeviceImgList(HTTPMethodView):

    @doc.summary("获取指定APP下指定设备下的图库列表")
    @doc.consumes({"view": {"app": str, "device": str}}, location="body")
    def post(self, request):
        app = request.json.get('app', '')
        device = request.json.get('device', '')
        img_list = APPDeviceImgList.iter_files(
            '{path}/static'.format(path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
            app=app,
            device=device)
        return response.json({'code': 0, 'data': img_list})

    @staticmethod
    def iter_files(root_dir, app, device) -> []:
        img_list = []
        for root, dirs, files in os.walk(root_dir):
            for file in files:
                file_name = os.path.join(root, file)
                tmp = app + '/' + device
                if tmp in file_name and file_name.endswith('.jpg'):
                    img_list.append(file_name.split('/ruyangmao/')[-1])
        return img_list


blueprint.add_route(APPDeviceImgList.as_view(), '/app_device_img_list', strict_slashes=True)
